package com.example.up;

import android.os.Environment;
import android.util.Log;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.Serializable;

import okio.Buffer;
import okio.Okio;
import okio.Sink;
import okio.Source;

/**
 * Created by yinghao on 2017/2/10.
 * Email：yhaowa@outlook.com
 * <p>
 * 处理文件分割
 */

class FileAccess implements Serializable {

    private Source mSource;
    private long mFileLength; //文件长度
    int mOffset; //读取位置
    static String TEMP_PATH = Environment.getExternalStorageDirectory().getAbsolutePath() + "/" + "temp";


    {
        File tempDir = new File(TEMP_PATH);
        if (!tempDir.exists()) {
            tempDir.mkdir();
        }
    }

    FileAccess(File file) {
        try {
            mSource = Okio.source(file);
            mOffset = 0;
            mFileLength = file.length();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
    }

    File getNextBlockFile(long blockSize) {
        if (mOffset >= mFileLength) {
            return null;
        }
        File tempFile = new File(TEMP_PATH, "temp" + System.currentTimeMillis() + ".mp4");
        Sink sink;
        Buffer buf = new Buffer();
        long[] readCounts = new long[]{0};
        long readCount;
        try {
            sink = Okio.sink(tempFile);
            do {
                readCount = mSource.read(buf, 2048);
                readCounts[0] += readCount;
                sink.write(buf, readCount);
            } while (readCounts[0] < blockSize && readCount == 2048);
            mOffset += readCounts[0];
            return tempFile;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }
}